#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QDebug>
#include <QSqlQuery>
#include <QSqlError>
#include <QMessageBox>
#include <QPixmap>
#include <QDir>
#include <QFile>
#include <QLineEdit>
#include <QPushButton>

MainWindow::MainWindow(QWidget *parent, int userId, const QString &userType)
    : QMainWindow(parent),
      ui(new Ui::MainWindow),
      m_userId(userId),
      m_userType(userType)
{
    ui->setupUi(this);
    disconnectAllButtons();  // 调用方法
    setupUI();
    setupDatabase();
    loadProducts();
}

void MainWindow::disconnectAllButtons()  // 添加方法实现
{
    QList<QPushButton*> buttons = findChildren<QPushButton*>();
    foreach (QPushButton* btn, buttons) {
        disconnect(btn, &QPushButton::clicked, 0, 0);
    }
}

MainWindow::~MainWindow()
{
    if(db.isOpen()) {
        db.close();
    }
    QSqlDatabase::removeDatabase(QSqlDatabase::defaultConnection);
    delete ui;
}

void MainWindow::setupUI()
{
    setWindowTitle("鲜花销售系统 - 主界面");
    resize(1000, 600);

    // 创建搜索框
    QLineEdit *searchBox = new QLineEdit();
    searchBox->setPlaceholderText("输入商品名称搜索...");
    searchBox->setClearButtonEnabled(true);
    connect(searchBox, &QLineEdit::textChanged, this, &MainWindow::onSearchTextChanged);

    // 创建购物车按钮
    cartButton = new QPushButton("购物车", this);
    cartButton->setStyleSheet(
        "QPushButton {"
        "   background-color: #4a90e2;"
        "   color: white;"
        "   border: none;"
        "   border-radius: 5px;"
        "   padding: 10px 20px;"
        "   font-size: 14px;"
        "}"
        "QPushButton:hover {"
        "   background-color: #3a7bc8;"
        "}"
    );

    // 创建商品评价按钮
    QPushButton *commentButton = new QPushButton("商品评价", this);
    commentButton->setStyleSheet(
        "QPushButton {"
        "   background-color: #6c757d;"
        "   color: white;"
        "   border: none;"
        "   border-radius: 5px;"
        "   padding: 10px 20px;"
        "   font-size: 14px;"
        "}"
        "QPushButton:hover {"
        "   background-color: #5a6268;"
        "}"
    );

    // 创建顶部布局容器
    QWidget *headerContainer = new QWidget();
    QHBoxLayout *headerLayout = new QHBoxLayout(headerContainer); // 正确创建布局并设置父对象
    headerLayout->setContentsMargins(0, 0, 0, 0); // 移除默认边距

    // 添加控件到顶部布局
    headerLayout->addWidget(searchBox);
    headerLayout->addStretch();
    headerLayout->addWidget(commentButton);
    headerLayout->addWidget(cartButton);

    // 获取主布局并添加顶部容器
    QVBoxLayout *mainLayout = qobject_cast<QVBoxLayout*>(ui->centralwidget->layout());
    if (mainLayout) {
        mainLayout->insertWidget(0, headerContainer); // 插入到顶部
    }

    // 连接按钮信号
    connect(cartButton, &QPushButton::clicked, this, &MainWindow::on_cartButton_clicked);
    connect(commentButton, &QPushButton::clicked, [this]() {
        commentWidget *cw = new commentWidget(m_userId, this);
        cw->exec();
        delete cw;
    });
    connect(ui->ordersButton, &QPushButton::clicked, [this]() {
        orderManager *orderDialog = new orderManager(this, m_userId);
        orderDialog->exec();
        delete orderDialog;
    });

    // 设置商品表格
    ui->productsTable->setColumnCount(5);
    ui->productsTable->setHorizontalHeaderLabels({"商品图片", "商品名称", "价格", "库存", "ID"});
    ui->productsTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->productsTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->productsTable->horizontalHeader()->setStretchLastSection(true);
    ui->productsTable->verticalHeader()->setVisible(false);
    ui->productsTable->setColumnWidth(0, 150);

    connect(ui->productsTable->selectionModel(), &QItemSelectionModel::selectionChanged,
            this, &MainWindow::onProductSelected);

    // 创建商品详情区域
    QWidget *productDetailsWidget = new QWidget();
    productDetailsLayout = new QVBoxLayout(productDetailsWidget);
    QPushButton *addToCartButton = new QPushButton("加入购物车", this);
    connect(addToCartButton, &QPushButton::clicked, this, &MainWindow::on_addToCartButton_clicked);
    productDetailsLayout->addWidget(addToCartButton);

    if (mainLayout) {
        mainLayout->addWidget(productDetailsWidget);
    }
}

void MainWindow::on_addToCartButton_clicked()
{
    QItemSelectionModel *selectionModel = ui->productsTable->selectionModel();
    if (!selectionModel->hasSelection()) {
        QMessageBox::warning(this, "警告", "请先选择商品");
        return;
    }

    int row = selectionModel->selectedRows().first().row();
    int productId = ui->productsTable->item(row, 4)->text().toInt();

    QSqlQuery checkQuery(db);
    checkQuery.prepare("SELECT quantity FROM Cart WHERE user_id = ? AND product_id = ?");
    checkQuery.addBindValue(m_userId);
    checkQuery.addBindValue(productId);

    if (checkQuery.exec() && checkQuery.next()) {
        QSqlQuery updateQuery(db);
        updateQuery.prepare("UPDATE Cart SET quantity = quantity + 1 "
                          "WHERE user_id = ? AND product_id = ?");
        updateQuery.addBindValue(m_userId);
        updateQuery.addBindValue(productId);

        if (!updateQuery.exec()) {
            QMessageBox::critical(this, "错误", "更新购物车失败: " + updateQuery.lastError().text());
            return;
        }
    } else {
        QSqlQuery insertQuery(db);
        insertQuery.prepare("INSERT INTO Cart (user_id, product_id, quantity) "
                          "VALUES (?, ?, 1)");
        insertQuery.addBindValue(m_userId);
        insertQuery.addBindValue(productId);

        if (!insertQuery.exec()) {
            QMessageBox::critical(this, "错误", "添加到购物车失败: " + insertQuery.lastError().text());
            return;
        }
    }

    QMessageBox::information(this, "成功", "商品已添加到购物车!");
}

void MainWindow::on_cartButton_clicked()
{
    Cart *cartDialog = new Cart(this, m_userId);
    cartDialog->exec();
    delete cartDialog;
}

void MainWindow::setupDatabase()
{
    if(QSqlDatabase::contains(QSqlDatabase::defaultConnection)) {
        db = QSqlDatabase::database();
    } else {
        db = QSqlDatabase::addDatabase("QSQLITE");
        db.setDatabaseName("flower_shop.db");
    }

    if (!db.open()) {
        QMessageBox::critical(this, "错误", "无法连接数据库: " + db.lastError().text());
        return;
    }
}

void MainWindow::loadProducts(const QString &filter)
{
    ui->productsTable->setRowCount(0);

    QSqlQuery query;
    if (filter.isEmpty()) {
        query.prepare("SELECT product_id, name, price, stock, image_path, description FROM products WHERE status = '在售'");
    } else {
        query.prepare("SELECT product_id, name, price, stock, image_path, description FROM products WHERE status = '在售' AND name LIKE ?");
        query.addBindValue("%" + filter + "%");
    }

    if (!query.exec()) {
        QMessageBox::critical(this, "错误", "查询失败: " + query.lastError().text());
        return;
    }

    int row = 0;
    while (query.next()) {
        ui->productsTable->insertRow(row);

        int productId = query.value("product_id").toInt();
        QString name = query.value("name").toString();
        double price = query.value("price").toDouble();
        int stock = query.value("stock").toInt();
        QString imagePath = query.value("image_path").toString();
        QString description = query.value("description").toString();

        QString resourcePath = ":" + imagePath;
        QPixmap pixmap(resourcePath);

        if (pixmap.isNull()) {
            pixmap = QPixmap(":/default/default_product.jpg");
            qDebug() << "无法加载资源图片:" << resourcePath;
        }

        pixmap = pixmap.scaled(120, 120, Qt::KeepAspectRatio, Qt::SmoothTransformation);

        QLabel *imageLabel = new QLabel();
        imageLabel->setPixmap(pixmap);
        imageLabel->setAlignment(Qt::AlignCenter);
        ui->productsTable->setCellWidget(row, 0, imageLabel);

        ui->productsTable->setItem(row, 1, new QTableWidgetItem(name));
        ui->productsTable->setItem(row, 2, new QTableWidgetItem(QString("¥%1").arg(price, 0, 'f', 2)));
        ui->productsTable->setItem(row, 3, new QTableWidgetItem(QString::number(stock)));
        ui->productsTable->setItem(row, 4, new QTableWidgetItem(QString::number(productId)));

        row++;
    }

    ui->productsTable->setColumnHidden(4, true);
}

void MainWindow::onProductSelected(const QItemSelection &selected, const QItemSelection &deselected)
{
    Q_UNUSED(deselected);

    if (selected.indexes().isEmpty()) {
        return;
    }

    int row = selected.indexes().first().row();
    int productId = ui->productsTable->item(row, 4)->text().toInt();

    QSqlQuery query;
    query.prepare("SELECT name, price, description, image_path FROM products WHERE product_id = ?");
    query.addBindValue(productId);

    if (!query.exec() || !query.next()) {
        QMessageBox::warning(this, "警告", "无法获取产品详情");
        return;
    }

    QString name = query.value("name").toString();
    double price = query.value("price").toDouble();
    QString description = query.value("description").toString();
    QString imagePath = query.value("image_path").toString();

    ui->productNameLabel->setText(name);
    ui->productPriceLabel->setText(QString("价格: ¥%1").arg(price, 0, 'f', 2));
    ui->productDescriptionLabel->setText(description.isEmpty() ? "暂无描述" : description);

    QString resourcePath = ":" + imagePath;
    QPixmap pixmap(resourcePath);

    if (pixmap.isNull()) {
        pixmap = QPixmap(":/default/default_product.jpg");
        qDebug() << "无法加载详情图片:" << resourcePath;
    }

    pixmap = pixmap.scaled(ui->productImageLabel->width(), ui->productImageLabel->height(),
                          Qt::KeepAspectRatio, Qt::SmoothTransformation);
    ui->productImageLabel->setPixmap(pixmap);
}

void MainWindow::onSearchTextChanged(const QString &text)
{
    loadProducts(text);
}
